#include <assert.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <libxml/parser.h>
#include <libxml/tree.h>

#include <xmlsec/buffer.h>
#include <xmlsec/xmldsig.h>

#include "common.h"

int main(int argc, char **argv) {
  xmlDocPtr doc, prop;
  xmlNodePtr root;
  xmlSecDSigReferenceCtxPtr r;
  xmlSecBufferPtr buf;
  int i;
  xmlSecDSigCtxPtr ds;
  
  assert(argc == 2);
  libSetup();
  doc = xmlParseFile(argv[1]);
  assert(doc);
  root = xmlDocGetRootElement(doc);
  assert(root);
  ds = processSolicitation(root);
  prop = ds->userData;
  xmlDocDump(stdout, prop);
  fprintf(stderr, "signedinfo refs %d\n", xmlSecPtrListGetSize(&ds->signedInfoReferences));
  if(1) {
    int fd;

    fd = open("/tmp/proposition-signed-c.xml", O_TRUNC|O_CREAT|O_WRONLY, 0600);
    assert(fd >= 3);
    for(i = 0; i < xmlSecPtrListGetSize(&ds->signedInfoReferences); i++) {
      r = xmlSecPtrListGetItem(&ds->signedInfoReferences, i);
      assert(r);
      buf = xmlSecDSigReferenceCtxGetPreDigestBuffer(r);
      assert(buf);
      fprintf(stderr, "signedinfo reference %d (%d):\n", i, buf->size);
      write(2, buf->data, buf->size);
      write(fd, buf->data, buf->size);
      fprintf(stderr, "\n end signedinfo reference\n");
    }
    close(fd);
  }

  if(0 && ds->preSignMemBufMethod) {
    buf = &ds->preSignMemBufMethod->inBuf;
    assert(buf);
    fprintf(stderr, "inbuf %d:\n", buf->size);
    write(2, buf->data, buf->size);
    fprintf(stderr, "\n end inbuf\n");
    buf = &ds->preSignMemBufMethod->outBuf;
    assert(buf);
    fprintf(stderr, "outbuf %d:\n", buf->size);
    write(2, buf->data, buf->size);
    fprintf(stderr, "\n end outbuf\n");
  }

  return 0;
}
